// src/composables/useFileManager.js
import { ref, computed } from "vue";
import * as XLSX from "xlsx";
import JSZip from "jszip";
import { useFilesStore } from "src/stores/files-store";
import { createFile, deleteFile, getFiles, getDrawData } from "src/api/api";

export function useFileManager(userId, selectedProject, $q) {
  const filesStore = useFilesStore();
  const files = ref([]);
  const openMenus = ref({});
  const uploadOption = ref("import");

  // 从后端获取文件列表
  const fetchFiles = async () => {
    try {
      const response = await getDrawData({
        project_id: selectedProject,
        file_id: 7,
      });
      files.value = response.data;
    } catch (error) {
      console.error("Failed to fetch files:", error);
    }
  };

  // 初始化文件列表
  const initFiles = async () => {
    if (filesStore.hasFilesForProject(selectedProject)) {
      files.value = filesStore.getFilesForProject(selectedProject);
      return;
    }
    files.value = [];
    const response = await getFiles(selectedProject);
    if (response.status === 200) {
      const contentDisposition = response.headers.get("content-disposition");
      const blob = await response.data;

      if (contentDisposition && contentDisposition.includes("filename")) {
        const zip = new JSZip();
        try {
          const unzipped = await zip.loadAsync(blob);
          const filesList = [];
          if (unzipped.files["file_info.json"]) {
            const jsonData = await unzipped.files["file_info.json"].async("string");
            const fileInfo = JSON.parse(jsonData);

            for (const filename of Object.keys(unzipped.files)) {
              const fileData = await unzipped.files[filename].async("blob");
              if (filename.endsWith(".xlsx") || filename.endsWith(".xls")) {
                const fileObject = new File([fileData], filename, {
                  type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                });
                const fileId = fileInfo.find(file => file.filename === filename)?.id;
                const header_row = fileInfo.find(file => file.filename === filename)?.header_row;

                if (fileId) {
                  filesList.push({
                    id: fileId,
                    file: fileObject,
                    header_row: header_row,
                  });
                }
              }
            }
          }
          filesStore.setFilesForProject(selectedProject, filesList);
          files.value = filesList;
        } catch (error) {
          console.error("Failed to unzip file:", error);
        }
      } else {
        $q.notify({ type: "warning", message: "请上传文件" });
      }
    } else {
      $q.notify({ type: "negative", message: "获取文件列表失败" });
    }
  };

  // 删除文件
  const handleDeleteFile = async (file) => {
    $q.dialog({
      title: "请确认",
      message: `您确定要删除文件吗？`,
      ok: { label: "确认", color: "negative" },
      cancel: { label: "取消" },
    }).onOk(async () => {
      const res = await deleteFile(file.id);
      if (res.data.code == 200) {
        filesStore.clearFilesForProject(selectedProject);
        await initFiles();
        $q.notify({ type: "positive", message: "文件删除成功" });
      } else {
        $q.notify({ type: "error", message: "文件删除失败" });
      }
    });
  };

  return {
    files,
    openMenus,
    uploadOption,
    fetchFiles,
    initFiles,
    handleDeleteFile,
  };
}
